package com.fengye.provider;

import com.fengye.config.PropertyConfigHelper;
import com.fengye.model.RemoteRequest;
import com.fengye.serialization.NettyDecodeHandler;
import com.fengye.serialization.NettyEncodeHandler;
import com.fengye.serialization.common.SerializeType;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author fengye
 * @Date 2023/2/13 13:56
 **/
public class NettyServer {

    private final static Logger logger = LoggerFactory.getLogger(NettyServer.class);

    /** 单例服务 */
    private static NettyServer nettyServer = new NettyServer();

    private Channel channel;

    /** 服务端boss线程组 */
    private EventLoopGroup bossGroup;

    /** 服务端worker线程组 */
    private EventLoopGroup workerGroup;

    /** 序列化类型配置信息 */
    private SerializeType serializeType = PropertyConfigHelper.getSerializeType();

    private NettyServer() { }

    public static NettyServer singleton() { return nettyServer; }

    /**
     * 启动Netty服务
     * @param port
     */
    public void start(final int port) {
        synchronized (NettyServer.class) {
            // 说明已经启动了
            if(bossGroup != null || workerGroup != null) {
                logger.info("Netty server started");
                return;
            }
            // 用于建立链接
            bossGroup = new NioEventLoopGroup();
            // 用于处理任务
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 注册解码器
                            socketChannel.pipeline().addLast(new NettyDecodeHandler(RemoteRequest.class, serializeType));
                            // 注册编码器
                            socketChannel.pipeline().addLast(new NettyEncodeHandler(serializeType));
                            // 注册服务端业务逻辑处理器，具体的调用逻辑
                            socketChannel.pipeline().addLast(new NettyServerInvokeHandler());
                        }
                    });

            try {
                // 服务启动
                channel = serverBootstrap.bind(port).sync().channel();
                logger.info("Netty server started.");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 服务停止
     */
    public void stop() {
        if(channel == null) {
            logger.info("Netty server stopped");
            throw new RuntimeException("Netty Server stopped");
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        channel.closeFuture().syncUninterruptibly();
    }
}
